
app.controller('UserListCtrl', ['$scope','$state','$rootScope','$stateParams','$modal', function($scope,$state,$rootScope,$stateParams,$modal) {
    var tree;
    $scope.selectGroupId = $stateParams.selectGroupId;
    $scope.startIndex=0;
    $scope.batchSize=25;
    $scope.totalCount = 0;
    $scope.filter = {name:"group",value:$scope.selectGroupId};
    $scope.group = null;
    $scope.users;
    $scope.getUsersByGroup = function() {
        requestServlet("getUserList",{filter:JSON.stringify($scope.filter),searchValue:$scope.searchValue,startIndex:$scope.startIndex,batchSize:$scope.batchSize},function(rs){
            $scope.totalCount = rs.totalCount;
            if($scope.startIndex==0) {
                $scope.users = rs.list;
            }else{
                $scope.users = $scope.users.concat(rs.list);
            }
            if(rs.list.length<$scope.batchSize){
                $scope.isLoad = true;
            }
        },function(msg){});
    }
    $scope.getUsersByGroup();
    $scope.groups;
    $scope.teams;
    $scope.myGroups;
    requestServlet("getGroupTree",{},function(rs){
        $scope.groups = rs.groups;
        $scope.teams = rs.teams;
        $scope.myGroups = rs.myGreoups;
    },function(msg){});
    $scope.scrollEvent= function(){
        $scope.startIndex = $scope.startIndex + $scope.batchSize;
        $scope.getUsersByGroup();
    }
    $scope.groups_tree = tree = {};
    $scope.group_handler_branch;
    $scope.group_handler = function(branch) {
        $scope.startIndex=0;
        $scope.isLoad=false;
        if($scope.group_handler_branch==branch){
            $scope.group_handler_branch.selected=false;
            $scope.group_handler_branch = null;
            $scope.filter = {name:"group",value:-1};
            $scope.group = null;
            $scope.getUsersByGroup();
        }else {
            $scope.group_handler_branch = branch;
            if($scope.my_group_handler_branch!=null){
                $scope.my_group_handler_branch.selected=false;
                $scope.my_group_handler_branch = null;
            }
            if($scope.teams_handler_branch!=null){
                $scope.teams_handler_branch.selected=false;
                $scope.teams_handler_branch = null;
            }
            $scope.selectGroupId = branch.id;
            $scope.filter = {name:"group",value:$scope.selectGroupId};
            $scope.group = branch;
            $scope.getUsersByGroup();
        }
    };
    $scope.my_groups_tree = tree = {};
    $scope.my_group_handler_branch;
    $scope.my_group_handler = function(branch) {
        $scope.startIndex=0;
        $scope.isLoad=false;
        if($scope.my_group_handler_branch==branch){
            $scope.my_group_handler_branch.selected=false;
            $scope.my_group_handler_branch = null;
            $scope.filter = {name:"group",value:-1};
            $scope.group = null;
            $scope.getUsersByGroup();
        }else {
            $scope.my_group_handler_branch = branch;
            if ($scope.group_handler_branch != null) {
                $scope.group_handler_branch.selected = false;
                $scope.group_handler_branch = null;
            }
            if ($scope.teams_handler_branch != null) {
                $scope.teams_handler_branch.selected = false;
                $scope.teams_handler_branch = null;
            }
            $scope.selectGroupId = branch.id;
            $scope.filter = {name: "group", value: $scope.selectGroupId};
            $scope.group = branch;
            $scope.getUsersByGroup();
        }
    };
    $scope.teams_tree = tree = {};
    $scope.teams_handler_branch;
    $scope.teams_handler = function(branch) {
        $scope.startIndex=0;
        $scope.isLoad=false;
        if($scope.teams_handler_branch==branch){
            $scope.teams_handler_branch.selected=false;
            $scope.teams_handler_branch = null;
            $scope.filter = {name:"group",value:-1};
            $scope.group = null;
            $scope.getUsersByGroup();
        }else {
            $scope.teams_handler_branch = branch;
            if ($scope.group_handler_branch != null) {
                $scope.group_handler_branch.selected = false;
                $scope.group_handler_branch = null;
            }
            if ($scope.my_group_handler_branch != null) {
                $scope.my_group_handler_branch.selected = false;
                $scope.my_group_handler_branch = null;
            }
            $scope.selectGroupId = branch.id;
            $scope.filter = {name: "group", value: $scope.selectGroupId};
            $scope.group = branch;
            $scope.getUsersByGroup();
        }
    };
    $scope.clean_group_handler = function() {
        $scope.startIndex=0;
        $scope.isLoad=false;
        if($scope.group_handler_branch!=null){
            $scope.group_handler_branch.selected=false;
            $scope.group_handler_branch=null;
        }
        if($scope.teams_handler_branch!=null){
            $scope.teams_handler_branch.selected=false;
            $scope.teams_handler_branch=null;
        }
        if($scope.my_group_handler_branch!=null){
            $scope.my_group_handler_branch.selected=false;
            $scope.my_group_handler_branch=null;
        }
        $scope.filter = {name:"group",value:-1};
        $scope.group = null;
        $scope.getUsersByGroup();
    };

    $scope.searchUserList= function(e){
            if(e==null){
                $scope.startIndex=0;
                $scope.isLoad=false;
                $scope.clean_group_handler();
                $scope.filter = {name:"group",value:-1};
                $scope.getUsersByGroup();
            }else{
                $scope.startIndex=0;
                $scope.isLoad=false;
                $scope.clean_group_handler();
                var keycode = window.event?e.keyCode:e.which;
                if(keycode==13){
                    $scope.filter = {name:"group",value:-1};
                    $scope.getUsersByGroup();
                }
            }
    }

}]);


var userName = "";
app.controller('UserProfilesCtrl', ['$scope','$state','$stateParams','$modal','$rootScope', function($scope,$state,$stateParams,$modal,$rootScope) {
	$scope.userprofiles;
    requestServlet("getUserInfo",{user:$stateParams.user},function(rs){
        $scope.userprofiles = rs;
    },function(msg){});
    $scope.tab='news';

    $scope.setTab=function(tab){
        $scope.tab = tab;
    }
    $scope.tabClass=function(tab){
        if($scope.tab == tab){
            return  "active"
        }
    }
	$scope.open = function (url,size) {
      var modalInstance = $modal.open({
        templateUrl: url,
        controller: 'chanagPasswordInstanceCtrl',
        size: size
      });
    
    };
	$scope.chanagPassword = function (url,size) {
		  $scope.open(url,size);
    };
	userName = $scope.userInfo.userName;
    $scope.reload = function(){
        $state.reload();
    }
    $scope.pictureUpload = function (){
        var modalInstance = $modal.open({
            templateUrl: 'tpl/picture_upload.html',
            controller: 'pictureUpload',
            resolve: {
                deps: ['$ocLazyLoad',
                    function( $ocLazyLoad){
                        return $ocLazyLoad.load('ngImgCrop').then(
                            function(){
                                return $ocLazyLoad.load('js/controllers/imgcrop.js');
                            }
                        );
                    }]
            }
        });
        modalInstance.result.then(function (image) {
            $rootScope.userPhotoTimestamp = $rootScope.userPhotoTimestamp+1;
        }, function () {
            //dismiss
        });
    }
}]);



app.controller('chanagPasswordInstanceCtrl', ['$scope', '$modalInstance','$state', function($scope, $modalInstance,$state) {
    $scope.ok = function () {
		var rs;
			$.ajax({
					url: "/suite/plugins/servlet/ChanageUserPassword",
					   type:"post",
					   data:{user:userName,oldPassword:$("#oldPassword").val(),newPassword:$("#newPassword").val(),confirmNewPassword:$("#confirmNewPassword").val()},
					   async:false,
						   success: function (rstext) {
								rs = rstext;
								if(rs==1){
									alert("密码修改成功。")
									$modalInstance.close();	
								}else if(rs==2){
									alert("旧密码不正确。")
								}else if(rs==3){
									alert("新密码和确认新密码不一致。")
								}else if(rs==4){
									alert("新密码不可与旧密码相同。")
								}else if(rs==5){
									alert("新密码规则不符合要求。")
								}
								
							},
							error: function () {
						   }
				});
		    
	}
    $scope.cancel = function () {
      $modalInstance.close();
    };
  }]);

  app.controller('UserProfilesNewsCtrl', ['$scope','$http','$state','$stateParams','toaster','$modal', function($scope,$http,$state,$stateParams,toaster,$modal) {
	moment.locale($scope.selectLangCode);
	
	//切换新闻类型
	$scope.filterValue = "userPublish";
	//查询新闻
	$scope.newss;$scope.startIndex=0;$scope.batchSize=25;
	$scope.isLoad=false;
	$scope.getNews = function(){
		requestServlet("viewNews",{startIndex:$scope.startIndex,batchSize:$scope.batchSize,searchType:$scope.filterValue,searchNewsText:$scope.searchNewsText,user:$scope.userprofiles.userName},function(rs){
			if($scope.startIndex==0) {
				$scope.newss = rs.list;
			}else{
				$scope.newss = $scope.newss.concat(rs.list);
			}
			if(rs.list.length<$scope.batchSize){
				$scope.isLoad = true;
			}
		},function(msg){});
		requestServlet("getNewsCount",{},function(rs){
			$scope.newsCount = rs;
		},function(msg){});
	}
	$scope.getNews();
	//搜索新闻
	$scope.searchNews= function(e){
		var keycode = window.event?e.keyCode:e.which;
		if(keycode==13){
			$scope.startIndex=0;
			$scope.isLoad=false;
			$scope.getNews();
		}
	}
	$scope.clickSearchNews= function(){
		$scope.startIndex=0;
		$scope.isLoad=false;
		$scope.getNews();
	}
	//滚动刷新
	$scope.scrollEvent= function(){
		$scope.startIndex = $scope.startIndex + $scope.batchSize;
		$scope.getNews();
	}
	//浏览新闻标记
	$scope.browseNews = function(news_id,my_is_browse_news,my_is_browse_new_comment){
		if(my_is_browse_news==0||my_is_browse_new_comment==0){
			requestServlet("browseNews",{news_id:news_id},function(rs){
			},function(msg){});
		}
		$("#news"+news_id).unbind("mouseenter");
	}
	//展开全文
	$scope.showContentFull = function(row_index){
		$scope.newss[row_index]["is_content_cut"]=false;
		$scope.newss[row_index]["is_content_full"]=true;
	}
	//收起全文
	$scope.hideContentFull = function(row_index){
		$scope.newss[row_index]["is_content_full"]=false;
		$scope.newss[row_index]["is_content_cut"]=true;
	}
	//鼠标划过参与者图标显示参与者
	$scope.showParticipants = function(news_id,row_index){
		window.isLink = true;
		$("#addParticipants"+news_id).select2({
			language: "zh-CN",
			ajax: {
				url: "/suite/plugins/servlet/searchUserAndGroup",
				delay: 250,
				dataType: 'json',
				data: function (params) {
					return {
						searchValue: params.term, // search term
						operator: 2,
						searchType: 'user'
					};
				},
				processResults: function (data, params) {
					return {results: data}
				},
				cache: true
			},
			placeholder: "添加参与者",
			minimumInputLength: 1,
			templateResult: formatState,
			templateSelection: formatRepoSelection,
			open:function(){
			}
		});
		$("#addParticipants"+news_id).on('select2:open',function(){
			window.isDrop = true;
		}).on('select2:close',function(){
			window.isDrop = false;
		});
		//获取参与者
		if($scope.newss[row_index]["participants"]==null){
			requestServlet("viewParticipants",{news_id:news_id},function(rs){
				$scope.newss[row_index]["participants"]=rs.list;
			},function(msg){});
		}
		var participantsLinkXY =$("#participantsLink"+news_id).offset();
		if($(window).height()-(participantsLinkXY.top-$(document.body).scrollTop()+20)>300){
			$("#participantsPanel"+news_id).css("top",participantsLinkXY.top+20);
			$("#participantsPanel"+news_id).css("left",participantsLinkXY.left);
		}else{
			$("#participantsPanel"+news_id).css("top",participantsLinkXY.top-100-$scope.newss[row_index]["participants"].length*25);
			$("#participantsPanel"+news_id).css("left",participantsLinkXY.left+30);
		}
		$("#participantsPanel"+news_id).show();
	}
	//鼠标离开隐藏参与者
	$scope.hideParticipants = function(news_id){
		window.isLink = false;
		setTimeout(function() {
			if (!window.isMoveDiv) {
				$("#participantsPanel" + news_id).fadeOut();
			}
		},200)
	}
	//鼠标停留参与者面板显示参与者面板
	$scope.showParticipantsPanel = function(news_id){
		window.isMoveDiv = true;
		$("#participantsPanel"+news_id).stop().fadeIn('fast');
	}
	//鼠标离开参与者面板隐藏参与者面板
	$scope.hideParticipantsPanel = function(news_id){
		window.isMoveDiv = false;
		if (!window.isLink && !window.isDrop) {
			$("#participantsPanel"+news_id).stop().fadeOut();
		}
	}
	//添加参与者
	$scope.addParticipants = function(news_id,row_index){
		var participants = $("#addParticipants"+news_id).select2("data");
		console.log(participants.length);
		if(participants.length>0) {
			requestServlet("addParticipants",{news_id: news_id, addParticipantsData: JSON.stringify(participants)},function(rs){
				$("#addParticipants" + news_id).select2('val', "");
				for (var i = 0; i < rs.list.length; i++) {
					$scope.newss[row_index]["participants"].push(rs.list[i]);
				}
				$scope.newss[row_index]["participant_count"] = $scope.newss[row_index]["participant_count"] + rs.list.length;
			},function(msg){});
		}
	}
	//删除新闻
	$scope.deleteNews = function(news_id,row_index,alertText){
		$scope.openPromptModal("common.prompt","common.ifDelete",function(){
			requestServlet("deleteNews",{news_id:news_id},function(rs){
				$("#news"+news_id).animate({
					width: 0,
					height: 0,
					padding: 0
				},1000,function(){
					$("#news"+news_id).remove();
					$scope.newss.splice(row_index,1);
				})
			},function(msg){});
		});
	}
	//内容的样式
	$scope.contentCss = function(have_to_comment){
		if(have_to_comment==1){
			return "text-crude";
		}
	}
	//是否收藏
	$scope.isFavorite = function(favorite,row_index){
		if(favorite==1){
			return "active";
		}
	}
	//收藏切换
	$scope.setFavorite = function(news_id,favorite,row_index){
		requestServlet("setFavorite",{is_favorite:favorite,news_id:news_id},function(rs){
			if($scope.filterValue!="favorite"){
				if (favorite == 1) {
					$scope.newss[row_index]["favorite_count"]--;
					$scope.newss[row_index]["favorite"] = 0;
				} else {
					$scope.newss[row_index]["favorite_count"]++;
					$scope.newss[row_index]["favorite"] = 1;
				}
			}else {
				$scope.getNews();
			}
		},function(msg){});
	}
	//显示评论输入
	$scope.showComment = function(id){
		$("#comment"+id).toggle();
		$("#commentText"+id).focus();
	}
	$scope.commentTextLeftCss = function(comment_count){
		if(comment_count>0){
			return "m-l-xxl";
		}
	}
	//显示全部评论
	$scope.viewAllComments = function(news_id,row_index){
			if($scope.newss[row_index]["is_show_comments"]==null||$scope.newss[row_index]["is_show_comments"]==0){
				$scope.newss[row_index]["is_show_comments"]=1;
			}else{
				$scope.newss[row_index]["is_show_comments"]=0;
			}
			requestServlet("viewComments",{news_id:news_id,is_show:$scope.newss[row_index]["is_show_comments"]},function(rs){
				$scope.newss[row_index]["comments"]=rs.list;
			},function(msg){});
	}
	$scope.commentAttachs={};
	$scope.selectedFileByComment = function (thiss){
		$scope.$apply(function($scope) {
			toaster.pop("wait","common.prompt","common.documentUpLoadLoading",2000,null,function(){});
		});
		var flag = $(thiss).attr("flag");
		var newsId = $(thiss).attr("newsId");
		uploadFileById(thiss,function(rs){
			$scope.$apply(function($scope) {
				toaster.pop("success","common.prompt","common.documentSuccess",null,null,function(){});
				if(rs.list[0].mimeType=='image'){
					if($scope.commentAttachs[newsId]==null){
						$scope.commentAttachs[newsId] = [rs.list[0]];
					}else{
						$scope.commentAttachs[newsId].splice(0, 0, rs.list[0]);
					}
				}else{
					if($scope.commentAttachs[newsId]==null){
						$scope.commentAttachs[newsId] = [rs.list[0]];
					}else{
						$scope.commentAttachs[newsId].push(rs.list[0]);
					}
				}
				console.log($scope.commentAttachs);
			});
		})
	}
	$scope.cleanCommentContent = function (content,newsId){
		if(content["folderId"]==9) {
			requestServlet("deleteContent", {id: content.id}, function () {
				$scope.commentAttachs[newsId]=null;
			}, function (msg) {
			});
		}else{
			$scope.commentAttachs[newsId]=null;
		}
	}
	//添加评论
	$scope.addComment = function(id,row_index){
		$scope.commentContent = $("#commentText"+id).val();
		if($scope.commentContent==""){
			$("#commentText"+id).focus();
			return;;
		}
		$scope.attachments=$scope.commentAttachs[id];
			$scope.commentData = {
				content: $scope.commentContent,
				news_id:id,
				attachments:$scope.attachments
			}
			requestServlet("newComment",{commentData:JSON.stringify($scope.commentData)},function(rs){
				if($scope.filterValue != "inComments") {
					if ($scope.newss[row_index]["comments"] == null) {
						$scope.newss[row_index]["comments"] = [rs];
					} else {
						$scope.newss[row_index]["comments"].splice(0, 0, rs);
					}
					$scope.newss[row_index]["comment_count"]++;
					$scope.newss[row_index]["my_comment_count"]++;
					$scope.newss[row_index]["have_to_comment"] = 0;
					$("#commentText" + id).val("");
					$scope.commentAttachs[id] = null;
					$("#comment" + id).hide();
				}else{
					$scope.getNews();
				}
			},function(msg){});
	}
	setTimeout(function(){
		$("#processModelInput").select2({
			language: "zh-CN",
			placeholder: $("#selectProcessModelText").val()
		});
	},0)
	//文件预览
	$scope.documentsView = function(id,attachments){
		if(attachments==null){
			attachments = $scope.documents
		}
		var documentIds=[];
		var documentId;
		var viewIndex =0;
		for(var i=0;i<attachments.length;i++){
				documentIds.push(attachments[i].id);
				if(attachments[i].id==id){
					documentId =  attachments[i].id;
					viewIndex = i;
				}
		}
		var modalInstance = $modal.open({
			templateUrl: 'tpl/documents_view_modal.html',
			controller: 'documentsViewModalCtrl',
			size: "docView",
			resolve: {
				type: function () {return "preview"},
				documentIds: function () {return documentIds},
				scope: function () {return $scope},
				viewIndex: function () {return viewIndex},
				documentId:function () {return documentId}
			}
		});
	}
}]);
/*
         * Javascript base64_encode() base64加密函数
           用于生成字符串对应的base64加密字符串
         * 吴先成  www.51-n.com ohcc@163.com QQ:229256237
         * @param string str 原始字符串
         * @return string 加密后的base64字符串
        */
        function base64_encode(str){
                var c1, c2, c3;
                var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";                
                var i = 0, len= str.length, string = '';

                while (i < len){
                        c1 = str.charCodeAt(i++) & 0xff;
                        if (i == len){
                                string += base64EncodeChars.charAt(c1 >> 2);
                                string += base64EncodeChars.charAt((c1 & 0x3) << 4);
                                string += "==";
                                break;
                        }
                        c2 = str.charCodeAt(i++);
                        if (i == len){
                                string += base64EncodeChars.charAt(c1 >> 2);
                                string += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
                                string += base64EncodeChars.charAt((c2 & 0xF) << 2);
                                string += "=";
                                break;
                        }
                        c3 = str.charCodeAt(i++);
                        string += base64EncodeChars.charAt(c1 >> 2);
                        string += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
                        string += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
                        string += base64EncodeChars.charAt(c3 & 0x3F)
                }
                        return string
        }
        /*
         * Javascript base64_decode() base64解密函数
           用于解密base64加密的字符串
         * 吴先成  www.51-n.com ohcc@163.com QQ:229256237
         * @param string str base64加密字符串
         * @return string 解密后的字符串
        */
        function base64_decode(str){
                var c1, c2, c3, c4;
                var base64DecodeChars = new Array(
                        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
                        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
                        -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57,
                        58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0,  1,  2,  3,  4,  5,  6,
                        7,  8,  9,  10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
                        25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
                        37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1,
                        -1, -1
                );
                var i=0, len = str.length, string = '';

                while (i < len){
                        do{
                                c1 = base64DecodeChars[str.charCodeAt(i++) & 0xff]
                        } while (
                                i < len && c1 == -1
                        );

                        if (c1 == -1) break;

                        do{
                                c2 = base64DecodeChars[str.charCodeAt(i++) & 0xff]
                        } while (
                                i < len && c2 == -1
                        );

                        if (c2 == -1) break;

                        string += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4));

                        do{
                                c3 = str.charCodeAt(i++) & 0xff;
                                if (c3 == 61)
                                        return string;

                                c3 = base64DecodeChars[c3]
                        } while (
                                i < len && c3 == -1
                        );

                        if (c3 == -1) break;

                        string += String.fromCharCode(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2));

                        do{
                                c4 = str.charCodeAt(i++) & 0xff;
                                if (c4 == 61) return string;
                                c4 = base64DecodeChars[c4]
                        } while (
                                i < len && c4 == -1
                        );

                        if (c4 == -1) break;

                        string += String.fromCharCode(((c3 & 0x03) << 6) | c4)
                }
                return string;
        }
